package router

import (
	"github.com/gin-gonic/gin"
	"go-admin-auth/app/http/handler/admin"
	"go-admin-auth/conf"
	"go-admin-auth/themes"
	"io/fs"
	"net/http"
	"strings"
)

type appServer struct {
	theme string

	staticFs   fs.FS
	fileServer http.Handler

	ginEngine *gin.Engine
}

var AppServer *appServer

func (f appServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	upath := r.URL.Path
	//if !strings.HasPrefix(upath, "/") {
	//	upath = "/" + upath
	//}

	//if strings.HasSuffix(upath, "/") {
	//	upath += "index.html"
	//}
	if upath == "/" {
		upath += "index.html"
	}

	if strings.HasPrefix(upath, "/themes/default") {
		upath = strings.Replace(upath, "/themes/default/", "", 1)
	}
	upath = strings.TrimLeft(upath, "/")
	_, err := f.staticFs.Open(upath)
	if err != nil {
		f.ginEngine.ServeHTTP(w, r)
	} else {

		r.URL.Path = upath
		f.fileServer.ServeHTTP(w, r)
	}
}

func init() {
	AppServer = NewServer()
	AppServer.SetupRouter()
}

func NewServer() *appServer {
	subFS, _ := fs.Sub(themes.DefaultTheme, "default")

	s := new(appServer)
	s.theme = conf.GetEnvDft("APP_THEME", "default")

	s.staticFs = subFS
	s.fileServer = http.FileServer(http.FS(subFS))

	s.ginEngine = gin.Default()

	return s
}

func (a appServer) SetupRouter() {
	//theme := a.theme
	// 静态文件
	//a.ginEngine.StaticFile("/favicon.ico", fmt.Sprintf("./themes/%s/favicon.ico", theme)) // 单文件

	//a.ginEngine.Static("/themes", "./themes/")                          // 目录下的文件
	//a.ginEngine.Static("/dist", fmt.Sprintf("./themes/%s/dist", theme)) // 目录下的文件
	//a.ginEngine.Static("/src", fmt.Sprintf("./themes/%s/src", theme))   // 目录下的文件
	//a.Engine.StaticFS("/more_static", http.Dir("my_file_system"))  // 目录中的文件，定制file.System服务

	//a.ginEngine.GET("/", func(c *gin.Context) {
	//	c.Redirect(http.StatusMovedPermanently, fmt.Sprintf("/%s/index.html", a.theme))
	//})

	// admin 路由 /admin-api/
	adminRoute(a.ginEngine)
	innerRoute(a.ginEngine)

	// 伪rest， 为方便post和一些 按钮的get操作
	a.ginEngine.GET("/admin-api/v1/any", admin.AnyResourceHandler.Any)
	a.ginEngine.POST("/admin-api/v1/any", admin.AnyResourceHandler.Any)

	// 未匹配到任何路由
	a.ginEngine.NoRoute(func(c *gin.Context) {
		// ginEngine.HandleContext()
		c.AbortWithStatus(http.StatusNotFound)
	})
}
